package com.sayimo.maker.activity.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.activity.dao.BaseCutDao;
import com.sayimo.maker.activity.dao.BaseCutDetailDao;
import com.sayimo.maker.activity.service.BaseCutDetailService;
import com.sayimo.maker.activity.vo.BaseCut;
import com.sayimo.maker.activity.vo.BaseCutDetail;
import com.sayimo.maker.commons.Constant;


/**
 * @Copyright (c) 2016 广东省尚一互联网有限公司
 * @Project: schoolmallapi-2.0
 * @ClassName: BaseCutDetailServiceImpl.java
 * @Description: 砍价详情
 * @Author:	tanxin
 * @Date:2016年10月19日,下午3:17:07
 * @Version 1.0.0
 */
@Service(value="baseCutDetailService")
public class BaseCutDetailServiceImpl implements BaseCutDetailService{
	
	@Autowired
	private BaseCutDetailDao baseCutDetailDao;
	@Autowired
	private BaseCutDao baseCutDao;
	
	/**
	 * @Package com.sayimo.school.mall.module.base.service.impl
	 * @Author TANXIN
	 * @MethodName:selectBaseCutDetailByIdentifier
	 * @Description:根据标示符查询砍价详情信息
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2016年10月20日,上午11:03:07
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map selectBaseCutDetailByIdentifier(String identifier,Integer _customerId)
			throws ServiceException {
		Map resultMap = new HashMap();
		
		Map map=new HashMap();
		map.put("identifier", identifier);
		map.put("customerId", _customerId);
		List<BaseCutDetail> list=new ArrayList<BaseCutDetail>();
		try {
			list=baseCutDetailDao.selectBaseCutDetailByIdentifier(map);
			resultMap.put(Constant.DATA, list);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * @Package com.sayimo.school.mall.module.base.service.impl
	 * @Author TANXIN
	 * @MethodName:selectBaseCutDetailJoinByCustomerId
	 * @Description:根据会员id查询砍价活动参与人信息
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2016年10月20日,上午11:03:19
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map selectBaseCutDetailJoinByCustomerId(String identifier,Integer _customerId)
			throws ServiceException {
		Map resultMap = new HashMap();
		Map map=new HashMap();
		map.put("identifier", identifier);
		map.put("customerId", _customerId);
		List<BaseCutDetail> list=new ArrayList<BaseCutDetail>();
		try {
			list=baseCutDetailDao.selectBaseCutDetailJoinByCustomerId(map);
			resultMap.put(Constant.DATA, list);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * @Package com.sayimo.school.mall.module.base.service.impl
	 * @Author TANXIN
	 * @MethodName:addCutDetail
	 * @Description:发起人发起砍价插入砍价详情表
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2016年10月20日,下午2:12:36
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map addCutDetail(HttpServletRequest request)
			throws ServiceException {
		Map resultMap = new HashMap();
		String identifier=request.getParameter("identifier");
		Integer customerId=request.getParameter("customerId")==null||"".equals(request.getParameter("customerId"))
				?null:Integer.parseInt(request.getParameter("customerId"));
		
		if(StringUtils.isEmpty(identifier)||StringUtils.isEmpty(customerId)){//参数错误
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		Map map=new HashMap();
		map.put("identifier", identifier);
		
		List<BaseCut> baseCutList=new ArrayList<BaseCut>();
		try {
			baseCutList=baseCutDao.selectBaseCutByIdentifier(map);
			if(baseCutList.size()>0){
				if(baseCutList.get(0).getNumber()<=0){
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.GOODS_STOCK_LACK);
					return resultMap;
				}
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_NO_DATA);
				return resultMap;
			}
			//销售原价
			BigDecimal preferentialPrice=baseCutList.get(0).getPreferentialPrice();
			//销售最低价
			BigDecimal minPrice=baseCutList.get(0).getMinPrice();
			//砍价次数
			Integer cutTimes=baseCutList.get(0).getCutTimes();
			BaseCutDetail baseCutDetail=new BaseCutDetail();
			baseCutDetail.setIdentifier(identifier);
			baseCutDetail.setCustomerId(customerId);
			baseCutDetail.setCutPrice(new BigDecimal(0));
			baseCutDetail.setCurrentPrice(preferentialPrice);
			StringBuffer cutPriceList=new StringBuffer();
			double[] cutPriceListDou=getRandomMoneyList(preferentialPrice.doubleValue()-minPrice.doubleValue(),cutTimes);
			for(double x : cutPriceListDou){
				cutPriceList.append(x+",");
			}
			baseCutDetail.setCutPriceList(cutPriceList.toString());
			
			Map dataMap=new HashMap();
			int num=0;
			num=baseCutDetailDao.addCutDetail(baseCutDetail);
			if(num>0){
				dataMap.put(Constant.MSG, "保存成功");
				resultMap.put(Constant.DATA, dataMap);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.SYSTEM_ERROR);
			}
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	/**
	 * @Package com.sayimo.school.mall.module.base.service.impl
	 * @Author TANXIN
	 * @MethodName:addCutJoin
	 * @Description:参与人点击砍价，记录插入t_base_cut_join表
	 * @param request
	 * @return
	 * @throws ServiceException
	 * @Date 2016年10月20日,下午2:31:17
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map addCutJoin(HttpServletRequest request)
			throws ServiceException {
		Map resultMap = new HashMap();
		String identifier=request.getParameter("identifier");
		Integer customerId=request.getParameter("customerId")==null||"".equals(request.getParameter("customerId"))
				?null:Integer.parseInt(request.getParameter("customerId"));
		Integer joinCustomerId=request.getParameter("joinCustomerId")==null||"".equals(request.getParameter("joinCustomerId"))
				?null:Integer.parseInt(request.getParameter("joinCustomerId"));
		
		if(StringUtils.isEmpty(identifier)||StringUtils.isEmpty(customerId)||StringUtils.isEmpty(joinCustomerId)){//参数错误
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		Map map=new HashMap();
		map.put("identifier", identifier);
		map.put("customerId", customerId);
		List<BaseCutDetail> baseCutDetailList=new ArrayList<BaseCutDetail>();
		List<BaseCutDetail> baseCutJoinList=new ArrayList<BaseCutDetail>();
		try {
			
			Integer customerGoodsBuy =0;
			Integer preCustomerGoodsBuy =0;
			//获取会员在该砍价活动购买商品总数
			customerGoodsBuy = baseCutDetailDao.getCustomerCutPriceGoodsBuy(customerId,identifier);
			preCustomerGoodsBuy = baseCutDetailDao.getPreCustomerCutPriceGoodsBuy(customerId,identifier);
			//会员是否参与过活动，已购买过活动商品
			if(customerGoodsBuy!=0||preCustomerGoodsBuy!=0){
				resultMap.put(Constant.MSG, Constant.SYSTEM_ERROR_ISBUYCUT_MSG);
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR_ISBUYCUT);
				return resultMap;
			}
			
			
			//获取砍价详情
			baseCutDetailList=baseCutDetailDao.selectBaseCutDetailByIdentifier(map);
			String [] cutPriceListStr=baseCutDetailList.get(0).getCutPriceList().split(",");
			if(baseCutDetailList.size()>0){
				
				//获取参与人信息
				baseCutJoinList=baseCutDetailDao.selectBaseCutDetailJoinByCustomerId(map);
				if(baseCutJoinList.size()>=cutPriceListStr.length){
					resultMap.put(Constant.MSG, Constant.SYSTEM_ERROR_CUTTIMES_MAX_MSG);
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR_CUTTIMES_MAX);
					return resultMap;
				}
				
				
				map.put("joinCustomerId", joinCustomerId);
				//判断参与人是否已砍过价
				List<BaseCutDetail> isCutJoin=new ArrayList<BaseCutDetail>();
				isCutJoin=baseCutDetailDao.selectBaseCutDetailJoinByCustomerId(map);
				if(isCutJoin.size()>0){
					resultMap.put(Constant.MSG, Constant.SYSTEM_ERROR_ISCUTJOIN_MSG);
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR_ISCUTJOIN);
					return resultMap;
				}
				
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_NO_DATA);
				return resultMap;
			}
			BaseCutDetail baseCutDetail=new BaseCutDetail();
			//本次砍价金额
			double joinCutPrice=Double.parseDouble(cutPriceListStr[baseCutJoinList.size()]);
			baseCutDetail.setIdentifier(identifier);
			baseCutDetail.setCustomerId(customerId);
			baseCutDetail.setCutDetailId(baseCutDetailList.get(0).getId());
			baseCutDetail.setJoinCustomerId(joinCustomerId);
			baseCutDetail.setJoinCutPrice(new BigDecimal(joinCutPrice));
			//已砍金额加上本次砍价金额
			baseCutDetail.setCutPrice(new BigDecimal(baseCutDetailList.get(0).getCutPrice().doubleValue()+joinCutPrice));
			//当前价格减去本次砍价金额
			baseCutDetail.setCurrentPrice(new BigDecimal(baseCutDetailList.get(0).getCurrentPrice().doubleValue()-joinCutPrice));
			
			
			Map dataMap=new HashMap();
			int num=0;
			//修改砍价详情信息
			num=baseCutDetailDao.updateCutDetail(baseCutDetail);
			//插入参与砍价人员记录
			num=baseCutDetailDao.addCutJoin(baseCutDetail);
			if(num>0){
				dataMap.put(Constant.MSG, "砍价成功");
				dataMap.put("currentPrice", joinCutPrice);
				resultMap.put(Constant.DATA, dataMap);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.SYSTEM_ERROR);
			}
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	
	/**
	 * @Package com.sayimo.school.mall.module.base.service.impl
	 * @Author TANXIN
	 * @MethodName:getRandomMoneyList
	 * @Description:通过随机金额， 随机次数获得随机金额列表
	 * @param ranMoney
	 * @param ranNmu
	 * @return
	 * @Date 2016年10月20日,上午11:36:31
	 */
	public static double[] getRandomMoneyList(double ranMoney,int ranNmu) {
		//ranMoney 需随机金额  ranNmu  随机次数
		double leftMoney=ranMoney;
		int peoples=ranNmu;
		int num=ranNmu;
		double [] cutPriceList=new double [num];
		for(int i=1;i<=num;i++){
			double randomMoney =getRandomMoney(leftMoney,peoples);
			cutPriceList[i-1]=randomMoney;
			leftMoney=leftMoney-randomMoney;
			peoples=peoples-1;
		}
		return cutPriceList;
	}
	/**
	 * @Package com.sayimo.school.mall.module.base.service.impl
	 * @Author TANXIN
	 * @MethodName:getRandomMoney
	 * @Description:通过剩余金额， 剩余次数获得单次随机金额
	 * @param leftMoney
	 * @param peoples
	 * @return
	 * @Date 2016年10月20日,上午11:29:53
	 */
	public static double getRandomMoney(double leftMoney,int peoples) {
		//leftMoney 剩余金额，peoples 剩余次数
	    if (peoples == 1) {
	        peoples--;
	        return (double) Math.round(leftMoney * 100) / 100;
	    }
	    Random r     = new Random();
	    double min   = 0.01;
	    double max   = leftMoney /peoples * 2;
	    double money = r.nextDouble() * max;
	    money = money < min ? min : money;
	    money = (double) Math.floor(money * 100) / 100;
	    return money;
	}
}
